package com.XDApp.xdbase.activitys;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 快速注册/忘记密码/绑定手机号
 * @author chenghao
 *
 */
public class RegistFirstActivity extends BaseActivity implements OnClickListener {
	/** 是否为注册 */
	public static final String PARAM_IS_REGISTER = "is_register";
	private final String TAG = "RegistFirstActivity";
	private ImageView iv_back;
	private TextView tv_title;
	private Button bt_goto;
	private EditText et_username;

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_regist_first);

		iv_back = (ImageView) findViewById(R.id.title_back);
		tv_title = (TextView) findViewById(R.id.title_text);
		bt_goto = (Button) findViewById(R.id.bt_registfirst);
		et_username = (EditText) findViewById(R.id.username);

	}

	@Override
	protected void initEvents() {
		bt_goto.setOnClickListener(this);
		bt_goto.setClickable(false);
		iv_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		if (getIntent().getBooleanExtra(PARAM_IS_REGISTER, true)) {
			tv_title.setText("快速注册");
		} else {
			tv_title.setText("获取验证码");
		}

		et_username.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
				bt_goto.setTextColor(Color.parseColor("#777777"));
				bt_goto.setClickable(false);
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(et_username.getText().toString().trim())) {
					bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
					bt_goto.setTextColor(Color.parseColor("#777777"));
					bt_goto.setClickable(false);
					return;
				}
				bt_goto.setBackgroundResource(R.drawable.bt_login_press);
				bt_goto.setTextColor(Color.WHITE);
				bt_goto.setClickable(true);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_registfirst:// 下一步
			String phone = et_username.getText().toString().trim();
			/**
			 * 判断输入的是手机号还是邮箱地址.
			 */
			if (phone.contains("@")) {
				/**
				 * 邮箱地址
				 */
				Log.e("test", "使用邮箱地址");
				if (isEmail(phone)) {
					// 合法，进行下一步，将账号存储到本地，并上传一份到服务器
					Log.e("test", "使用邮箱注册");
					getData(true, phone);
				} else {
					// 不合法，提示用户输入合法的邮箱地址
					CRToast.show(RegistFirstActivity.this, "您输入的邮箱地址不合法");
					return;
				}

			} else {
				/**
				 * 手机号码
				 */
				Log.e("test", "使用手机号码地址");
				if (isMobilePhone(phone)) {
					// 合法，进行下一步，上传一份到服务器
					Log.e("test", "使用手机号注册");
					getData(false, phone);
				} else {
					// 不合法，提示用户
					CRToast.show(RegistFirstActivity.this, "您输入的手机号不合法");
					return;
				}

			}
			break;
		default:
			break;
		}
	}

	// TODO 访问网络获取数据
	private void getData(final boolean isEmail, final String phone) {
		if (CommonUtil.checkNetState(RegistFirstActivity.this)) {
			RequestParams params = new RequestParams();
			if (isEmail) {
				params.put("email", phone);
			} else {
				params.put("phone", phone);
			}

			if (!getIntent().getBooleanExtra(PARAM_IS_REGISTER, true)) {
				params.put("flag", "1");
			}

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.GETVERIFYCODE, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.e(TAG, content);
					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					JSONObject obj1 = new JSONObject().parseObject(data);
					String isUserReg = obj1.getString("isUserReg");
					Log.e(TAG, isUserReg);

					if ("0".equals(isUserReg)) {
						if (isEmail) {
							CRToast.show(RegistFirstActivity.this, "验证码已经发送给邮箱");
						} else {
							CRToast.show(RegistFirstActivity.this, "验证码已经发送给手机");
						}
						Intent intent = new Intent(RegistFirstActivity.this, RegistSecondActivity.class);
						intent.putExtra("phone", phone);
						intent.putExtra("is_email", isEmail);
						intent.putExtra(PARAM_IS_REGISTER,
								getIntent().getBooleanExtra(PARAM_IS_REGISTER, true));
						startActivity(intent);
						finish();
					} else {
						if (isEmail) {
							CRToast.show(RegistFirstActivity.this, "该邮箱已经被注册");
						} else {
							CRToast.show(RegistFirstActivity.this, "该手机号已经被注册");
						}
						return;
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(RegistFirstActivity.this, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	/**
	 * 判断手机号码是否合法.
	 */
	private boolean isMobilePhone(String address) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,2,5-9]))\\d{8}$");
		Matcher m = p.matcher(address);
		return m.matches();
	}

	/**
	 * 邮箱地址是否合法 判断
	 * 
	 * @param address
	 * @return
	 * 
	 */
	private boolean isEmail(String address) {
		String strPattern = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(address);
		return m.matches();

	}
}
